<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      ref="crud"
      v-model="form"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button type="warning" size="small" icon="el-icon-s-promotion" @click="openSendInfo">发送消息</el-button>
        <el-button type="warning" size="small" icon="el-icon-download" @click="$refs.exportComp.visible = true">导 出</el-button>
      </template>
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
    </avue-crud>
    <el-dialog ref="dialog" title="发送消息" append-to-body :visible.sync="showDialog" @close="closeDialog">
      <avue-form v-if="showDialog" ref="form" v-model="sendInfoform" :option="sendInfoOption"></avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" icon="el-icon-circle-close" @click="showDialog = false">取 消</el-button>
        <el-button size="small" type="primary" icon="el-icon-circle-plus-outline" @click="sendInfo">保 存</el-button>
      </span>
    </el-dialog>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
    <export-comp ref="exportComp" page-api-url="mes-alert/strategy-message/page-query" :option="option" :page="page" :query="query" file-name="消息通知"></export-comp>
  </basic-container>
</template>

<script>
import { getList, getDetail, getAltStrategyType, getModule, getMessageDetail, sendMessage } from '@/api/earlyWarning/notify';
import { mapGetters } from 'vuex';
import exportComp from '@/components/export-comp';
import userTableConfig from '@/components/user-table-config/index.vue';
import userConfig from '@/mixins/userConfig';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
export default {
  components: {
    exportComp,
    userTableConfig,
    CommonModalTemplate
  },
  mixins: [userConfig()],
  data() {
    return {
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 15,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'calc(100vh - 436px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 18,
        searchMenuPosition: 'right',
        border: true,
        index: true,
        indexLabel: '序号',
        selection: true,
        dialogClickModal: false,
        searchLabelWidth: 100,
        searchSpan: 6,
        addBtn: false,
        editBtn: false,
        viewBtn: true,
        delBtn: false,
        menu: true,
        menuWidth: 100,
        columnBtn: false,
        column: [
          {
            label: '消息编码',
            prop: 'strategyCode',
            order: 1
          },
          {
            label: '消息名称',
            prop: 'strategyName',
            search: true,
            order: 2
          },
          {
            label: '消息类型',
            prop: 'strategyType',
            search: true,
            order: 3,
            type: 'select',
            dicData: [],
            change: (val) => {
              if (val.value) {
                //获取预警策略指标字典
                let metricId = this.findObject(this.option.column, 'metricId');
                getModule(val.value).then(
                  (res) => {
                    let data = this._get(res, 'data.data', []);
                    metricId.dicData = this._map(data, (item) => {
                      item.children = this._map(item.children, (childrenItem) => {
                        return {
                          label: childrenItem.value,
                          value: childrenItem.id
                        };
                      });
                      return {
                        label: item.value,
                        value: item.key,
                        children: item.children
                      };
                    });
                  },
                  (error) => {
                    metricId.dicData = [];
                  }
                );
              }
            }
          },
          {
            label: '指标/事件',
            prop: 'metricId',
            hide: true,
            type: 'cascader',
            dicData: [],
            search: true,
            order: 4
          },
          {
            label: '指标/事件',
            prop: 'metricName',
            order: 4
          },
          {
            label: '描述',
            prop: 'content',
            span: 24,
            type: 'textarea',
            rows: 3,
            order: 7,
            search: true,
            overHidden: true
          },
          {
            label: '通知方式',
            prop: 'notifyType',
            type: 'select',
            dicData: [{ label: '邮件', value: 'EMAIL' }],
            order: 5
          },
          {
            label: '提醒日期',
            prop: 'warningTime',
            search: true,
            order: 6,
            type: 'date',
            searchType: 'datetimerange',
            format: 'yyyy-MM-dd',
            valueFormat: 'yyyy-MM-dd',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
          }
        ]
      },
      data: [],
      sendInfoOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 150,
        column: [
          {
            label: '通知人',
            prop: 'notifyUserName',
            type: 'search',
            disabled: true,
            appendClick: () => {
              this.openUserCommonModal();
            },
            rules: [
              {
                required: true,
                trigger: 'submit',
                message: '请输入通知人'
              }
            ]
          },
          {
            label: '手机号码',
            prop: 'notifyPhone',
            disabled: true,
            rules: [
              {
                required: true,
                trigger: 'submit',
                validator: (rule, value, callback) => {
                  if (!value) {
                    callback(new Error('请输入手机号码'));
                  } else {
                    let phones = value.split(',');
                    let phonereg = false;
                    for (let i = 0; i < phones.length; i++) {
                      let reg = /^1(?:3\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8\d|9\d)\d{8}$/;
                      if (phones[i] && !reg.test(phones[i])) {
                        phonereg = true;
                        break;
                      } else {
                        phonereg = false;
                      }
                    }
                    if (phonereg) {
                      callback(new Error('请输入正确手机号码'));
                    } else {
                      callback();
                    }
                  }
                }
              }
            ]
          },
          {
            label: '消息类型',
            prop: 'metricType',
            type: 'select',
            dicData: [],
            disabled: true
          },
          {
            label: '预警指标值',
            prop: 'metricValue',
            disabled: true
          },
          {
            label: '消息名称',
            prop: 'strategyName',
            disabled: true
          },
          {
            label: '通知内容',
            prop: 'content',
            type: 'textarea',
            maxRows: 3,
            minRows: 3,
            span: 24
          }
        ]
      },
      showDialog: false,
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      timer: new Date().getTime(), //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
      noPhoneUser: [] //没有手机号码的用户
    };
  },
  computed: {
    ...mapGetters(['permission']),
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  created() {},
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
    //获取预警策略类型字典
    let strategyType = this.findObject(this.option.column, 'strategyType');
    let metricType = this.findObject(this.sendInfoOption.column, 'metricType');
    getAltStrategyType().then(
      (res) => {
        let data = this._get(res, 'data.data', []);
        strategyType.dicData = this._map(data, (item) => {
          return {
            label: item.dictKey,
            value: item.dictValue
          };
        });
        metricType.dicData = this._map(data, (item) => {
          return {
            label: item.dictKey,
            value: item.dictValue
          };
        });
      },
      (error) => {
        strategyType.dicData = [];
      }
    );
  },
  methods: {
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = this._get(res, 'data.data', {});
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      if (params.metricId) {
        params.metricId = params.metricId[1];
      }
      if (params.warningTime && params.warningTime.length > 0) {
        params.startTime = params.warningTime[0];
        params.endTime = params.warningTime[1];
        delete params.warningTime;
      }
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    openUserCommonModal() {
      this.modalName = 'userCommonModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择通知人',
        url: '/api/blade-system/user/page',
        isPage: true,
        rowSelectionType: 'multiple',
        columnDefs: [
          {
            label: '用户名',
            prop: 'account',
            search: true,
            searchSpan: 8
          },
          {
            label: '手机号码',
            prop: 'phone',
            search: true,
            searchSpan: 8
          },
          {
            label: '部门',
            prop: 'deptName'
          }
        ]
      };
    },
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'userCommonModal':
          this.sendInfoform.notifyUserId = rowData.map((item) => item.id);
          let notifyUserName = [];
          let notifyPhone = [];
          this.noPhoneUser = [];
          this._forEach(rowData, (item) => {
            if (item.account) {
              notifyUserName.push(item.account);
            }
            if (item.phone) {
              notifyPhone.push(item.phone);
            }
            if (item.account && !item.phone) {
              this.noPhoneUser.push(item.account);
            }
          });
          this.sendInfoform.notifyUserName = notifyUserName.join(',');
          this.sendInfoform.notifyPhone = notifyPhone.join(',');
          break;
        default:
          break;
      }
    },
    // 重新加载公用表格弹窗组件
    newKey() {
      this.timer = new Date().getTime();
    },
    openSendInfo() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择一条数据');
        return;
      }
      this.showDialog = true;
      getMessageDetail(this.selectionList[0].id).then((res) => {
        let data = this._get(res, 'data.data', {});
        this.sendInfoform.metricType = data.metricType;
        this.sendInfoform.metricValue = data.metricValue;
        this.sendInfoform.strategyName = data.strategyName;
        this.sendInfoform.content = data.content;
      });
    },
    sendInfo() {
      this.$refs.form.validate((valid, done) => {
        if (valid) {
          if (this.noPhoneUser.length > 0) {
            let noPhoneUsers = this.noPhoneUser.join('、');
            this.$confirm(`用户${noPhoneUsers}没有手机号码，请维护`, {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {});
            return;
          }
          let sendInfoform = {
            notifyUserIdList: this.sendInfoform.notifyUserId,
            content: this.sendInfoform.content,
            notifyPhoneList: this.sendInfoform.notifyPhone.split(',')
          };
          sendMessage(sendInfoform).then((res) => {
            this.$message.success(res.data.msg);
            this.showDialog = false;
            done();
          });
        }
      });
    },
    closeDialog() {
      this.$refs.form.resetFields();
      this.sendInfoform = {};
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-date-editor {
  justify-content: space-between;
  .el-input__icon {
    display: none;
  }
  input {
    width: 43%;
  }
}
</style>
